import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import TextbookList from '../views/TextbookList.vue'
import TextbookDetail from '../views/TextbookDetail.vue'
import PublishTextbook from '../views/PublishTextbook.vue'
import MyOrders from '../views/MyOrders.vue'
import Login from '../views/Login.vue'
import { ElMessage } from 'element-plus'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    meta: {
      title: '首页',
      requiresAuth: false
    }
  },
  {
    path: '/textbooks',
    name: 'TextbookList',
    component: TextbookList,
    meta: {
      title: '教材列表',
      requiresAuth: false
    }
  },
  {
    path: '/textbooks/:id',
    name: 'TextbookDetail',
    component: TextbookDetail,
    props: true,
    meta: {
      title: '教材详情',
      requiresAuth: false
    }
  },
  {
    path: '/publish',
    name: 'PublishTextbook',
    component: PublishTextbook,
    meta: {
      title: '发布教材',
      requiresAuth: true
    }
  },
  {
    path: '/orders',
    name: 'MyOrders',
    component: MyOrders,
    meta: {
      title: '我的订单',
      requiresAuth: true
    }
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: {
      title: '登录',
      requiresAuth: false
    }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - 二手教材交易平台`
  }
  
  // 检查是否需要登录
  if (to.meta.requiresAuth) {
    const user = localStorage.getItem('user')
    if (!user) {
      ElMessage.warning('请先登录')
      next('/login')
    } else {
      next()
    }
  } else {
    next()
  }
})

export default router


